// pages/my/wallet/index.js
import {
  getInfoApi,
  postWalletRechargeApi,
  getWalletLogApi
} from '../../../https/user'
import {
  rechargeList
} from '../../../constant/index'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isRecharge: false,
    isPassword: false,
    info: {},
    rechargeList: rechargeList,
    chekeRecharge: rechargeList[0],
    password: "",
    logList: []

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getInfo()
    this.getLogList()
  },
  // 获取所有记录
  async getLogList() {
    const getRes = await getWalletLogApi()
    console.log(getRes)
    if (getRes.code == 200) {
      this.setData({
        logList: getRes.data
      })
    }
  },


  // 获取用户 
  async getInfo() {
    const getRes = await getInfoApi()
    console.log(getRes)
    if (getRes.code == 200) {
      console.log(getRes.data)
      wx.setStorageSync('userData', getRes.data)
      this.setData({
        info: getRes.data
      })
    }
  },
  // 切换选择充值状态
  async changeRecharge(e) {
    console.log(e)
    const item = e.currentTarget.dataset.item
    this.setData({
      chekeRecharge: item
    })
  },

  // 点击充值按钮
  async bindRecharge() {
    console.log('点击充值了')
    // 打开充值验证界面
    // this.onClose()
    this.setData({
      isRecharge: false,
      isPassword: true
    })
  },

  // 输入框事件
  changePassword(e) {
    console.log(e)
    const password = e.detail.value
    this.setData({
      password
    })
  },
  // 验证充值
  async verify() {

    const password = this.data.password
    if (!password) {
      wx.showToast({
        title: '请输入密码验证',
        icon: 'error'
      })
      return
    }
    wx.showLoading({
      title: '充值中',
    })
    const amount = this.data.chekeRecharge.amount
    const postRes = await postWalletRechargeApi({
      amount,
      password
    })
    console.log(this.data.chekeRecharge)
    console.log(postRes)
    if (postRes.code == 200) {
      // 重新渲染页面
      await this.getInfo()
      await this.getLogList()
      await this.onClose()
      wx.showToast({
        title: '充值成功',
      })
    } else {
      setTimeout(() => {
        wx.showToast({
          title: postRes.message,
          icon: 'error'
        })
      }, 500)
    }

  },
  // 打开充值窗口
  async openRecharge() {
    this.setData({
      isRecharge: true
    })
  },
  // 关闭充值窗口
  async onClose() {
    const that = this
    this.setData({
      isRecharge: false,
      isPassword: false,
    })
    setTimeout(() => {
      that.setData({
        password: "",
        chekeRecharge: rechargeList[0]
      })
    }, 400)
  }
})